import { defineStore } from "pinia";
import pinia from "@/store/index"
import {userLogin, refreshUserInfo, LoginRequest} from "@/api/user"

export interface IUserState{
    username:string,
    accessToken: string,
    roles: string[]
    refreshToken?: string,
}

export const useUserStoreHook = defineStore("userinfo",{
    state: ():IUserState=> ({
        username:"大伟",
        accessToken: "",
        roles: ["common"]
    }),
    getters: {},
    actions: {
        storeUserLogin(data:LoginRequest) {
            return userLogin(data).then(res=>{
                this.username = res.username
                this.roles = res.roles
                this.accessToken = res.accessToken
                return res
            })
        },
        storeRefreshUserInfo(){
            if(this.username == "大伟" && this.accessToken != ""){
                refreshUserInfo({accessToken: this.accessToken})
                .then(res => {
                    this.username = res.username
                    this.roles = res.roles
                    this.accessToken = res.accessToken
                })
                .catch(() => {
                    this.accessToken = ""
                })
            }
        }
    },
    persist: {
        key: "userinfo",
        storage: sessionStorage,
        paths: ["accessToken"]
    }
})

export function useUserStore() {
    return useUserStoreHook(pinia)
}